package com.system.controller;

import com.github.pagehelper.PageInfo;
import com.system.po.ReservePlan;
import com.system.po.Upload;
import com.system.service.ReservePlandrawingService;
import com.system.service.UploadService;
import com.system.utils.DWGFileToPDFManager;
import com.system.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 应急预案图纸的处理
 */
@RequestMapping("ReservePlandrawing")
@Controller
@Api(description = "应急预案图纸的处理接口")
public class ReservePlandrawingController {
    public static final String FILE_PATH="C:\\file\\";

    @Autowired
    private ReservePlandrawingService reservePlandrawingServiceImpl;
    @Autowired
    private UploadService uploadServiceImpl;

    @RequestMapping(value = "selectReservePlandrawingList/{page}/{limit}",method = RequestMethod.GET)
    @ApiOperation("查询事故信息图纸List")
    @ResponseBody
    public Result selectReservePlandrawingList(@PathVariable(value = "page",required = true) Integer  page,
                                               @PathVariable(value = "limit",required = true) Integer limit){
        System.out.println("---------------selectReservePlandrawingList-----------------------");
        PageInfo<ReservePlan> reservePlandrawingList= reservePlandrawingServiceImpl.selectReservePlandrawingList(page,limit);
        return reservePlandrawingList.getSize()>0?Result.ok(reservePlandrawingList):Result.fail("查询失败");
    }

    @RequestMapping(value = "selectReservePlandrawingById/{id}",method = RequestMethod.GET)
    @ApiOperation("查询事故信息图纸通过id")
    @ResponseBody
    public Result selectReservePlandrawingById(@PathVariable("id") Integer id){
        System.out.println("---------------selectReservePlandrawingById-----------------------");
        ReservePlan reservePlandrawing= reservePlandrawingServiceImpl.selectReservePlandrawingById(id);
        return reservePlandrawing!=null?Result.ok(reservePlandrawing):Result.fail("查询失败");
    }



    //@RequestMapping(value = "addReservePlandrawing",method = RequestMethod.POST)
    //@ApiOperation("添加事故信息")
    //@Valid ReservePlan reservePlan,
    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    @ApiOperation("上传文件并返回上传记录表upload_files的主键id")
    @ResponseBody
    public Result addInformation(/*Errors errors, Map<String,Object> map,*/
                                 @RequestParam("file") MultipartFile myfile,
                                 HttpServletRequest request, HttpSession session) throws InterruptedException, IOException {
        File_Mkdir();
        String originalFilename=myfile.getOriginalFilename().trim();

        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String dateTime = new DateTime().toString("yyyy-MM-dd-HH-mm-ss");
        originalFilename =FILE_PATH+dateTime+"-"+ uuid+"-"+myfile.getOriginalFilename();
        System.out.println(originalFilename);



//        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);
//        Set<Callable<MultipartFile>> callables = new HashSet<Callable<MultipartFile>>();
       // File outFile = new File( originalFilename);
       // UploadThread uploadThread = new UploadThread(myfile,request);
//        callables.add(uploadThread);
//        fixedThreadPool.invokeAll(callables);
        reservePlandrawingServiceImpl.uploadAndDWGFileToPDFManager(myfile,originalFilename);


        String username = (String)SecurityUtils.getSubject().getPrincipal();
      if(username==null){
          throw new NullPointerException("请重新登陆！");
      }
      Upload upload=new Upload();
        upload.setUpload_user_name(username);
      upload.setUpload_file_path_name(originalFilename);



        int uploadRecord  =   uploadServiceImpl.adduploadRecordAndReturnId(upload);


      return Result.ok(upload.getId());
    }

    public void File_Mkdir(){
        File file = new File(FILE_PATH);
        if (!file.exists()) {
            file.mkdirs();
        }

    }


    @RequestMapping(value = "addReservePlandrawing",method = RequestMethod.POST)
    @ApiOperation("添加事故信息")
    @ResponseBody
    public Result addReservePlandrawing( ReservePlan reservePlan,Integer id){
System.out.println("---------------addReservePlandrawing-----------------------");
       Upload upload= uploadServiceImpl.selectUploadById(id);
       if(upload==null){
           throw new NullPointerException("文件不存在！请重新上传");
       }
        reservePlan.setDrawing_upload_filepath(upload.getUpload_file_path_name());
        reservePlan.setDrawing_upload_user_name(upload.getUpload_user_name());
       boolean reservePlandrawing= reservePlandrawingServiceImpl.addReservePlandrawing(reservePlan);
    return reservePlandrawing?Result.ok("添加成功"):Result.fail("添加失败");
    }

    @RequestMapping(value = "updateReservePlandrawing",method = RequestMethod.PUT)
    @ApiOperation("修改事故信息")
    @ResponseBody
    public Result updateReservePlandrawing( ReservePlan reservePlan, Integer id){
        Upload upload= uploadServiceImpl.selectUploadById(id);
        System.out.println(upload);
        if(upload==null){
            throw new NullPointerException("文件不存在！请重新上传");
        }


        reservePlan.setDrawing_upload_filepath(upload.getUpload_file_path_name());
        reservePlan.setDrawing_upload_user_name(upload.getUpload_user_name());
        System.out.println(reservePlan.getReserve_plan_id());
        boolean reservePlandrawing= reservePlandrawingServiceImpl.updateReservePlandrawingById(reservePlan);


        return reservePlandrawing?Result.ok("修改成功"):Result.fail("修改失败");
    }






    @RequestMapping(value = "filesUpload",method = RequestMethod.GET)
    @ApiOperation("上传页面")
    public String filesUpload(){

        return "admin/files-upload";
    }


    @RequestMapping(value = "DeleteReservePlandrawing/{id}",method = RequestMethod.DELETE)
    @ApiOperation("删除记录")
    @ResponseBody
    public Result DeleteReservePlandrawing(@PathVariable("id") Integer id){
        Integer delete=  reservePlandrawingServiceImpl.DeleteReservePlandrawing(id);
        return delete>0?Result.ok("删除成功"):Result.fail("删除失败");
    }




    /**
     * 下载文件
     * @param filename
     * @throws Exception
     */
    @RequestMapping(value = "/download",method = RequestMethod.GET)
    @ApiOperation("下载文件传入filename文件名")
    public ResponseEntity<byte[]> download(String filename) throws Exception {
        //body(文件的所有字节byte[]),
        String filepath = FILE_PATH + filename;
        File file = new File(filepath);

        if (file.exists()) {
            // 将文件加载为流
            InputStream in = new FileInputStream(file);
            byte[] body = new byte[in.available()];
            in.read(body);
            in.close();
            // headers 响应头，控制浏览器下载形式

            HttpHeaders headers = new HttpHeaders();
            headers.set("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));

            //  status 响应状态
            HttpStatus status = HttpStatus.OK;

            ResponseEntity<byte[]> responsebyte = new ResponseEntity<byte[]>(body, headers, status);
            return responsebyte;
        }
        return null;

    }
    // 转发应急预案图纸
    @RequestMapping( value = "/emergencyPlanDrawing")
    @ApiOperation(value = "转发应急预案图纸")
    @ResponseBody
    public ModelAndView drawing() throws Exception {
        ModelAndView mv2=new ModelAndView();
        mv2.setViewName("admin/emergencyPlanDrawing");
        return mv2;
    }
    // 转发图纸列表
    @RequestMapping( value = "/theDrawingList")
    @ApiOperation(value = "转发应急预案图纸")
    @ResponseBody
    public ModelAndView theDrawingList() throws Exception {
        ModelAndView mv2=new ModelAndView();
        mv2.setViewName("admin/theDrawingList");
        return mv2;
    }

}
